//
//  LHBaseWebViewController.m
//  EPA
//
//  Created by 卢浩 on 16/4/19.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHBaseWebViewController.h"
#import "LHNetWorkRequestManager.h"
#import "LHReadCommentController.h"
#import "LHDBManager.h"
#import "LHReadListModel.h"
#import "LHMenuViewController.h"

@interface LHBaseWebViewController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *webView;

@property (nonatomic,strong) UIBarButtonItem *collectBarButton;

@property (nonatomic,strong) NSString *htmlStr;

@end

@implementation LHBaseWebViewController

//页面打开,设置收藏按钮的标题
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setCollectBarButtonTitle];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    NSLog(@"%@",self.url);
    
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    webView.backgroundColor = [UIColor lightGrayColor];
    self.webView = webView;
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    UIBarButtonItem *collectItem = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:(UIBarButtonItemStylePlain) target:self action:@selector(collectAction)];
    self.collectBarButton = collectItem;
    UIBarButtonItem *commentItem = [[UIBarButtonItem alloc]initWithTitle:@"评论" style:(UIBarButtonItemStylePlain) target:self action:@selector(commentAction)];
    
    if (self.contentid) {
        self.navigationItem.rightBarButtonItems = @[commentItem,self.collectBarButton];
        [self showReadDetailVC];
    }else if (self.url){
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth=380;" //缩放系数
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height * (maxwidth/oldwidth);"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}

//收藏按钮事件
- (void)collectAction{
    if ([LHUserInfoManager shareManager].uid) {
        if ([self.collectBarButton.title isEqualToString:@"收藏"]) {
            BOOL isCollect = [[LHDBManager shareManager] InsertReadCollectWithReadListModel:self.model HtmlStr:self.htmlStr];
            [self setCollectBarButtonTitle];
            if (isCollect) {
                [self showAlertControllerManagerWithMessage:@"收藏成功"];
            }else{
                [self showAlertControllerManagerWithMessage:@"收藏失败"];
            }
        }else if ([self.collectBarButton.title isEqualToString:@"已收藏"]){
            //弹窗提示确定是否取消收藏
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要取消收藏吗?" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                BOOL isCancelCollect = [[LHDBManager shareManager] DeleteReadCollectWithContentID:self.contentid];
                [self setCollectBarButtonTitle];
                if (isCancelCollect) {
                    [self showAlertControllerManagerWithMessage:@"已取消收藏"];
                }else{
                    [self showAlertControllerManagerWithMessage:@"取消收藏失败"];
                }
            }]];
            [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
            [self presentViewController:alertC animated:YES completion:nil];
        }
    }else{
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未登陆哦!" preferredStyle:(UIAlertControllerStyleAlert)];
        [alertC addAction:[UIAlertAction actionWithTitle:@"登陆" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [[LHMenuViewController getMenuViewController] showLoginVC];
        }]];
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

//设置收藏按钮的标题
- (void)setCollectBarButtonTitle{
    NSArray *collectAllIDArr = [[LHDBManager shareManager] selectAllReadCollectContentID];
    if ([collectAllIDArr containsObject:self.contentid]) {
        self.collectBarButton.title = @"已收藏";
    }else{
        self.collectBarButton.title = @"收藏";
    }
}

- (void)showAlertControllerManagerWithMessage:(NSString *)message{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
    [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil]];
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)commentAction{
    LHReadCommentController *readCommentVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LHReadCommentController"];
    readCommentVC.contentid = self.contentid;
    [self.navigationController pushViewController:readCommentVC animated:YES];
}

- (void)showReadDetailVC{
    NSDictionary *bodyDict = @{@"contentid":self.contentid,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"auth":[LHUserInfoManager shareManager].auth,@"version":@"3.0.2"};
    [LHNetWorkRequestManager requestUrl:[NSURL URLWithString:READCONTENT_URL] Methed:POST Params:bodyDict Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDict = dict[@"data"];
            NSDictionary *shareinfoDict = dataDict[@"shareinfo"];
            NSString *htmlStr = dataDict[@"html"];
            NSString *titleStr = shareinfoDict[@"title"];
//            NSLog(@"%@",htmlStr);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.navigationItem.title = titleStr;
                [self.webView loadHTMLString:htmlStr baseURL:nil];
                self.htmlStr = htmlStr;
                if (htmlStr.length == 0) {
                    [self showReadDetailVC];
                }
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
